package com.dff.jrfw.remote;

import android.net.SSLCertificateSocketFactory;

import com.dff.jrfw.MyApplication;
import com.dff.jrfw.common.Constant;
import com.dff.jrfw.utils.SharedPreferenceUtils;
import com.dff.jrfw.utils.Util;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.CertificatePinner;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitUtilsTwo {

    private RetrofitUtilsTwo() {
        getRetrofit();
    }

    private static Retrofit retrofit;

    public static synchronized Retrofit getRetrofit() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Util.logLength("xxx", message);
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY);
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request updateRequest;
                String token = (String) SharedPreferenceUtils.getInstance().get(MyApplication.getContext(), Constant.TOKEN, "");
                long currentTimeMillis = System.currentTimeMillis();
                Request originalRequest = chain.request();
//                if(originalRequest.url().toString().endsWith("uas/api/authorization/login")){
//                    token = "Basic TlNUQzpWVkIxVG1sVlVURlNMemxyTkhoc2VtNXdObFJaUVQwOQ==";
//                }
                updateRequest = originalRequest.newBuilder()
                        .addHeader(Constant.TOKEN, token)
                        .addHeader(Constant.timestamp, String.valueOf(currentTimeMillis))
                        .removeHeader("User-Agent")
                        .addHeader("User-Agent","Android")
                        .build();
                return chain.proceed(updateRequest);
            }
        };
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .addInterceptor(httpLoggingInterceptor)
                //.retryOnConnectionFailure(true)
                .connectTimeout(30 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(30 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(30 * 1000, TimeUnit.MILLISECONDS);
//        try {
//            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
//            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
//            keyStore.load(null);
//            InputStream stream = MyApplication.getContext().getAssets().open("");
//            Certificate certificate = certificateFactory.generateCertificate(stream);
//            keyStore.setCertificateEntry("alias",certificate);
//            stream.close();
//            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//            trustManagerFactory.init(keyStore);
//            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
//            SSLContext sslContext = SSLContext.getInstance("TLS");
//            sslContext.init(null,trustManagers,new SecureRandom());
//            final List<X509TrustManager> x509trustManagers = new ArrayList<X509TrustManager>();
//            for (TrustManager tm : trustManagers) {
//                if (tm instanceof X509TrustManager) {
//                    x509trustManagers.add((X509TrustManager) tm);
//                }
//            }
//            X509TrustManager trustManager = new X509TrustManager() {
//
//                @Override
//                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
//
//                }
//
//                @Override
//                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException, CertificateException {
//                    for (X509TrustManager tm : x509trustManagers) {
//                        tm.checkServerTrusted(x509Certificates, s);
//                    }
//                }
//
//                @Override
//                public X509Certificate[] getAcceptedIssuers() {
//                    return new X509Certificate[0];
//                }
//            };
//            sslContext.init(null, new TrustManager[]{trustManager}, null);
//            builder.sslSocketFactory(sslContext.getSocketFactory(),trustManager)
//                    .hostnameVerifier((hostname, session) -> true);
//        } catch (NoSuchAlgorithmException | KeyManagementException | CertificateException | KeyStoreException | IOException e) {
//            e.printStackTrace();
//        }
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            X509TrustManager x509TrustAllaManager = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            };
            TrustManager[] trustAllCerts = new TrustManager[]{x509TrustAllaManager};
            sslContext.init(null,trustAllCerts,new SecureRandom());
            builder.sslSocketFactory(sslContext.getSocketFactory(), x509TrustAllaManager)
            .hostnameVerifier((hostname, session) -> true);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
        OkHttpClient okHttpClient = builder.build();
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(ApiConfig.BASE_URL_TWO)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }


    public static ApiService getService() {
        ApiService service = (ApiService) RetrofitUtilsTwo.getInstance().retrofit.create(ApiService.class);
        return service;
    }


//    /**
//     * 调用单例对象
//     */
//    private static RetrofitUtils getInstance() {
//        return RDClientInstance.instance;
//    }
//
//    /**
//     * 创建单例对象
//     */
//    private static class RDClientInstance {
//        static RetrofitUtils instance = new RetrofitUtils();
//    }


    private static volatile RetrofitUtilsTwo mInstance;


    /**
     * 调用单例对象
     */
    public static RetrofitUtilsTwo getInstance() {
        if (mInstance == null) {
            synchronized (RetrofitUtilsTwo.class) {
                if (mInstance == null) {
                    mInstance = new RetrofitUtilsTwo();
                }
            }
        }
        return mInstance;
    }


}
